package com.x.erp.service;

import com.alibaba.fastjson.JSON;
import com.x.erp.dao.*;
import com.x.erp.model.Car;
import com.x.erp.model.CarImage;
import com.x.erp.model.Market;
import com.x.erp.model.Model;
import com.x.erp.thirdparty.CarMappingThirdparty;
import com.x.erp.thirdparty.ModelMappingThirdparty;
import com.x.erp.thirdparty.SouHuCarInfo;
import com.x.erp.util.Constant;
import com.x.erp.util.SouHuApi;
import com.x.erp.util.SouHuResult;
import com.x.framework.service.BaseService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Component
public class SouHuCarService extends BaseService {

	private Logger logger = LoggerFactory.getLogger(SouHuCarService.class);

	@Autowired
	private ModelMappingThirdpartyDao modelMappingThirdpartyDao;

	@Autowired
	private CarMappingThirdpartyService carMappingThirdpartyService;

	@Autowired
	private MarketDao marketDao;

	@Autowired
	private CarImageDao carImageDao;

	@Autowired
	private ModelDao modelDao;

	@Autowired
	private SouHuApi souHuApi;

	@Autowired
	private CarDao carDao;

	// 发布车源
	public void updateCarSaleState20(Car car) {
		if(StringUtils.isEmpty(Constant.SOUHU_URL) || Constant.SOUHU_URL.contains("test")){
			return;
		}
		if(car != null && StringUtils.isNotEmpty(car.getCarId())) {
			//获取车辆信息
			car =  getCarInfo(car);
			if(car == null){
				logger.info("获取车辆信息失败！");
				return;
			}
			//判断价格是否为面议
			if (car.getCarRetailPrice() != null && car.getCarRetailPrice() == new BigDecimal(0)){
				logger.info("该车辆为面议车辆，不推送搜狐汽车！");
				return;
			}
			//判断是否为新车（新车不推送搜狐汽车）
			if (car.getCarLicenceState() != null && car.getCarLicenceState() == 3){
				logger.info("该车辆为新车，不推送搜狐汽车！");
				return;
			}
			//获取车源信息
			SouHuCarInfo souHuCarInfo = getSouHuCarInfo(car);
			if(souHuCarInfo == null){
				logger.info("获取车辆信息失败！");
				return;
			}
			logger.info(JSON.toJSONString(souHuCarInfo.getInfo()));
			//判断是否为第一次发布车源
			List<CarMappingThirdparty> selectCarMappingThirdpartList = selectCarMappingThirdpartList(car);
			//如果不是第一次发布车源，则设为上架状态
			if(selectCarMappingThirdpartList != null && selectCarMappingThirdpartList.size() > 0){
				try {
					SouHuResult souHuResult = souHuApi.insertOrUpdateCar(souHuCarInfo, car.getCarId(), 1);
					if (souHuResult == null){
						logger.info("搜狐重新上架或修改信息返回数据有误！");
						return;
					}
					if(!souHuResult.getCode().equals("0") && !souHuResult.getCode().equals("1")){
						logger.info("搜狐重新上架或修改信息失败，提示码：" + souHuResult.getCode() + "  ，提示信息：" + souHuApi.getErrorMsg(souHuResult.getCode()));
						return;
					}
					logger.info("搜狐重新上架架或修改信息成功！ID ：" + car.getCarId());
				} catch (Exception e) {
					logger.error("搜狐重新上架或修改信息失败！" , e);
					return;
				}
			}else {//如果是第一次发布车源则添加车源
				// 发布车源
				Integer id = null;
				try {
					SouHuResult souHuResult = souHuApi.insertOrUpdateCar(souHuCarInfo, car.getCarId(), 1);
					if (souHuResult == null){
						logger.info("搜狐发布车源返回数据有误！");
						return;
					}
					if(!souHuResult.getCode().equals("0") && !souHuResult.getCode().equals("1")){
						logger.info("搜狐发布车源失败，提示码：" + souHuResult.getCode() + "  ，提示信息：" + souHuApi.getErrorMsg(souHuResult.getCode()));
						return;
					}
				} catch (Exception e) {
					logger.error("搜狐发布车源返回数据有误！", e);
					return;
				}
				//将返回的车辆id存起来
				CarMappingThirdparty carMappingThirdparty = new CarMappingThirdparty();
				carMappingThirdparty.setCarId(car.getCarId());
				carMappingThirdparty.setCarThirdpartyId(0);
				carMappingThirdparty.setCarType(2);
				CarMappingThirdparty carMappingThirdpartBack = carMappingThirdpartyService.insertCarMappingThirdpart(carMappingThirdparty);
				if (carMappingThirdpartBack != null){
					logger.info("搜狐发布车源成功！启辕车辆ID ：" + carMappingThirdpartBack.getCarId());
				}
			}
		}
	}

	// 设为下架
	public void updateCarSaleState30(Car car){
		if(StringUtils.isEmpty(Constant.SOUHU_URL) || Constant.SOUHU_URL.contains("test")){
			return;
		}
		if(car != null && StringUtils.isNotEmpty(car.getCarId())){
			try {
				//获取车辆信息
				car =  getCarInfo(car);
				if(car == null){
					logger.info("获取车辆信息失败！");
					return;
				}
				//判断价格是否为面议
				if (car.getCarRetailPrice() != null && car.getCarRetailPrice() == new BigDecimal(0)){
					logger.info("该车辆为面议车辆，不推送搜狐汽车！");
					return;
				}
				//判断是否为新车（新车不推送搜狐汽车）
				if (car.getCarLicenceState() != null && car.getCarLicenceState() == 3){
					logger.info("该车辆为新车，不推送搜狐汽车！");
					return;
				}
				//获取车源信息
				SouHuCarInfo souHuCarInfo = getSouHuCarInfo(car);
				List<CarMappingThirdparty> selectCarMappingThirdpartList = selectCarMappingThirdpartList(car);
				if(selectCarMappingThirdpartList != null && selectCarMappingThirdpartList.size() > 0){
					SouHuResult souHuResult = souHuApi.insertOrUpdateCar(souHuCarInfo, car.getCarId(), 2);
					if (souHuResult == null){
						logger.info("搜狐下架车源返回数据有误！");
						return;
					}
					if(!souHuResult.getCode().equals("0") && !souHuResult.getCode().equals("1")){
						logger.info("搜狐下架车源车源失败，提示码：" + souHuResult.getCode() + "  ，提示信息：" + souHuApi.getErrorMsg(souHuResult.getCode()));
						return;
					}
					logger.info("搜狐下架车源成功！");
				}
			} catch (Exception e) {
				logger.error("搜狐下架车源失败！", e);
				return;
			}
		}
	}

	// 设为已售
	public void updateCarStockState40(Car car){
		if(StringUtils.isEmpty(Constant.SOUHU_URL) || Constant.SOUHU_URL.contains("test")){
			return;
		}
		if(car != null && StringUtils.isNotEmpty(car.getCarId())){
			try {
				//获取车辆信息
				car =  getCarInfo(car);
				if(car == null){
					logger.info("获取车辆信息失败！");
					return;
				}
				//判断价格是否为面议
				if (car.getCarRetailPrice() != null && car.getCarRetailPrice() == new BigDecimal(0)){
					logger.info("该车辆为面议车辆，不推送搜狐汽车！");
					return;
				}
				//判断是否为新车（新车不推送搜狐汽车）
				if (car.getCarLicenceState() != null && car.getCarLicenceState() == 3){
					logger.info("该车辆为新车，不推送搜狐汽车！");
					return;
				}
				//获取车源信息
				SouHuCarInfo souHuCarInfo = getSouHuCarInfo(car);
				List<CarMappingThirdparty> selectCarMappingThirdpartList = selectCarMappingThirdpartList(car);
				if(selectCarMappingThirdpartList != null && selectCarMappingThirdpartList.size() > 0){
					SouHuResult souHuResult = souHuApi.insertOrUpdateCar(souHuCarInfo, car.getCarId(), 3);
					if (souHuResult == null){
						logger.info("搜狐设为已售返回数据有误！");
						return;
					}
					if(!souHuResult.getCode().equals("0") && !souHuResult.getCode().equals("1")){
						logger.info("搜狐设为已售车源失败，提示码：" + souHuResult.getCode() + "  ，提示信息：" + souHuApi.getErrorMsg(souHuResult.getCode()));
						return;
					}
					logger.info("搜狐设为已售成功！");
				}
			} catch (Exception e) {
				logger.error("搜狐设为已售失败！", e);
				return;
			}
		}
	}

	// 删除车源
	public void deleteCarSouHu(Car car){
		if(StringUtils.isEmpty(Constant.SOUHU_URL) || Constant.SOUHU_URL.contains("test")){
			return;
		}
		if(car != null && StringUtils.isNotEmpty(car.getCarId())){
			try {
				SouHuCarInfo souHuCarInfo = new SouHuCarInfo();
				souHuCarInfo.setInfo("这辆车要删除");
				SouHuResult souHuResult = souHuApi.insertOrUpdateCar(souHuCarInfo, car.getCarId(), 4);
				if (souHuResult == null){
					logger.info("搜狐删除车源返回数据有误！");
					return;
				}
				if(!souHuResult.getCode().equals("0") && !souHuResult.getCode().equals("1")){
					logger.info("搜狐删除车源失败，提示码：" + souHuResult.getCode() + "  ，提示信息：" + souHuApi.getErrorMsg(souHuResult.getCode()));
					return;
				}
				logger.info("搜狐删除车源成功！");
			} catch (Exception e) {
				logger.error("搜狐删除车源失败！", e);
				return;
			}
		}
	}

	public List<CarMappingThirdparty> selectCarMappingThirdpartList(Car car){
		CarMappingThirdparty carMappingThirdparty = new CarMappingThirdparty();
		carMappingThirdparty.setCarId(car.getCarId());
		carMappingThirdparty.setCarType(2);
		List<CarMappingThirdparty> selectCarMappingThirdpartList = carMappingThirdpartyService.selectCarMappingThirdpartList(carMappingThirdparty);
		return selectCarMappingThirdpartList;
	}

	//获取搜狐车辆信息方法
	private SouHuCarInfo getSouHuCarInfo(Car car){

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//获取图片信息
		CarImage carImage = new CarImage();
		carImage.setCarId(car.getCarId());
		List<String> images = null;
		try {
			List<CarImage> carImages = carImageDao.selectCarImageList(carImage, 3);
			images = new ArrayList<>();
			if(carImages != null && carImages.size() > 0){
				String imageUrl = null;
				for (CarImage carImg : carImages) {
					imageUrl = Constant.FDFS_CONTENT_PATH + carImg.getImageUrl();
					if(carImg.getImageKey().equals("left_anterior")){
						images.add(0, imageUrl);
					}
					if(carImg.getImageKey().equals("driving_seat")){
						images.add(imageUrl);
					}
					if(carImg.getImageKey().equals("engine_bay")){
						images.add(imageUrl);
					}
					if(carImg.getImageKey().equals("gear_lever")){
						images.add(imageUrl);
					}
					if(carImg.getImageKey().equals("control_booth")){
						images.add(imageUrl);
					}
					if(carImg.getImageKey().equals("odograph")){
						images.add(imageUrl);
					}
					if(carImg.getImageKey().equals("open_trunk")){
						images.add(imageUrl);
					}
					if(carImg.getImageKey().equals("right_rear")){
						images.add(imageUrl);
					}
					if(carImg.getImageKey().equals("right_side")){
						images.add(imageUrl);
					}
					if(carImg.getImageKey().equals("tyre")){
						images.add(imageUrl);
					}
				}
			}
		} catch (Exception e) {
			logger.error("启辕获取图片失败", e);
			return null;
		}
		String image = StringUtils.join(images, ";");

		// 获取车型库关系
		ModelMappingThirdparty modelMappingThirdparty = new ModelMappingThirdparty();
		modelMappingThirdparty.setModelId(car.getModelId());
		modelMappingThirdparty.setModelType(2);
		Integer souHuModelId = null;
		try {
			List<ModelMappingThirdparty> modelMappingThirdpartyList = modelMappingThirdpartyDao.selectModelMappingThirdpartyList(modelMappingThirdparty);
			if (modelMappingThirdpartyList == null || modelMappingThirdpartyList.size() == 0){
				logger.info("获取车型库关系失败或启辕无此车型！");
				return null;
			}
			if (modelMappingThirdpartyList.get(0).getModelThirdpartyId() == 0){
				logger.info("搜狐车型库无此车型，发布失败！");
				return null;
			}
			souHuModelId = modelMappingThirdpartyList.get(0).getModelThirdpartyId();
		} catch (Exception e) {
			logger.error("获取车型库关系失败！", e);
			return null;
		}

		// 获取城市关系
		Market market = new Market();
		market.setMarketId(car.getMarketId());
		List<Market> marketList = null;
		try {
			marketList = marketDao.selectMarketList(market);
			if (marketList == null || marketList.size() == 0){
				logger.info("获取城市时获取市场信息失败！");
				return null;
			}
		} catch (Exception e) {
			logger.error("获取城市时获取市场信息失败！", e);
			return null;
		}
		String cityName = marketList.get(0).getCity().getCityName();
		String provinceName = marketList.get(0).getProvince().getProvinceName();

		// 获取档位个数
		Model model = new Model();
		model.setModelId(car.getModelId());
		List<Model> modelList = null;
		try {
			modelList = modelDao.selectModelList(model);
			if (modelList == null || modelList.size() == 0){
				logger.info("获取档位个数时获取车型失败！");
				return null;
			}
		} catch (Exception e) {
			logger.error("获取档位个数失败！", e);
			return null;
		}
		String gearboxNum = modelList.get(0).getModelGearNum();

		SouHuCarInfo souHuCarInfo = new SouHuCarInfo(car, souHuModelId, provinceName, cityName, gearboxNum, image);
		return souHuCarInfo;
	}

	//获取车辆信息方法
	private Car getCarInfo(Car car){
		try {
			Car selectCar = new Car();
			selectCar.setCarId(car.getCarId());
			car = carDao.selectCar(selectCar);
			if(car == null){
				logger.info("搜狐接口获取车辆信息失败！");
				return null;
			}
		} catch (Exception e) {
			logger.error("搜狐接口获取车辆信息失败！", e);
			return null;
		}
		return car;
	}


}
